#include "sdl_fliprgbasurface.h"

SDL_Surface * flipRGBASurface(SDL_Surface * img)
{
    Uint32 rmask, bmask, gmask, amask;
    rmask = img->format->Rmask;
    bmask = img->format->Gmask;
    gmask = img->format->Bmask;
    amask = img->format->Amask;

    SDL_Surface * cpy = SDL_CreateRGBSurface(SDL_RLEACCEL, img->w, img->h, 32, rmask, gmask, bmask, amask);

    //	int bpp = img->format->BytesPerPixel;

    SDL_LockSurface(cpy);

    for (int y = 0; y < img->h; y++)
        for (int x = 0; x < img->w; x++) {
            int iy = img->h - y - 1;
            Uint32 * pix = (Uint32 *) img->pixels + iy * img->w + x;
            Uint32 * pix2 = (Uint32 *) cpy->pixels + y * img->w + x;
            *pix2 = *(Uint32 *) pix;
        }

    SDL_UnlockSurface(cpy);
    return cpy;

}

SDL_Surface * OpenGL_convert(SDL_Surface * src)
{
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    Uint32 rmask = 0xff000000;
    Uint32 gmask = 0x00ff0000;
    Uint32 bmask = 0x0000ff00;
    Uint32 amask = 0x000000ff;
#else
    Uint32 rmask = 0x000000ff;
    Uint32 gmask = 0x0000ff00;
    Uint32 bmask = 0x00ff0000;
    Uint32 amask = 0xff000000;
#endif

    SDL_Surface * ret;
    SDL_Surface * inverted;

    ret = SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32, rmask, gmask, bmask, amask);
    //	SDL_LockSurface(ret);
    SDL_BlitSurface(src, &src->clip_rect, ret, &ret->clip_rect);
    //	SDL_UnlockSurface(ret);
    inverted = flipRGBASurface(ret);

    SDL_FreeSurface(src);
    SDL_FreeSurface(ret);
    return inverted;
}
